package com.kuang.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuang.demo.bean.acgBeanVo.BaseData;
import com.kuang.demo.bean.lhf.Topic;
import com.kuang.demo.bean.lhf.TopicExample;
import com.kuang.demo.mapper.TopicMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TopicServiceImp implements TopicService{

    @Autowired
    TopicMapper topicMapper;

    @Override
    public BaseData queryTopicList(Integer page, Integer limit, String sort,
                                   String order, String title, String subtitle) {
        //预编译的时候增加分页的sql语句
        PageHelper.startPage(page, limit);
        //设置排序的条件
        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause(sort+" "+order);

        //设置查询条件
        if (title != null && !"".equals(title)){
            topicExample.createCriteria().andTitleLike("%"+title+"%");
        }
        if (subtitle != null && !"".equals(subtitle)){
            topicExample.createCriteria().andSubtitleLike("%"+subtitle+"%");
        }
        //获取查询结果
        List<Topic> topics = topicMapper.selectByExample(topicExample);
        //可以在查询完成后获得pageInfo → 根据查询结果获得总条目数total
        PageInfo<Topic> adPageInfo = new PageInfo<>(topics);
        long total = adPageInfo.getTotal();

        //所需数据封装并返回
        return BaseData.data(topics,total);


    }

    @Override
    public void updateTopic(Topic topic) {
        TopicExample topicExample = new TopicExample();
        topicExample.createCriteria().andIdEqualTo(topic.getId());
        topicMapper.updateByExample(topic,topicExample);
    }

    @Override
    public void deleteTopic(Topic topic) {
        topicMapper.deleteByPrimaryKey(topic.getId());
    }

    @Override
    public Topic createTopic(Topic topic) {
        topic.setAddTime(new Date());
        topic.setDeleted(false);
        topic.setUpdateTime(new Date());
        topicMapper.insert(topic);

        return topic;
    }
}
